//
//  ZYHellp.m
//  Merchant
//
//  Created by apple on 16/3/29.
//  Copyright © 2016年 ibendi. All rights reserved.
//http://blog.csdn.net/likendsl/article/details/8348939  文件管理
//http://www.jianshu.com/p/9a34c1ee4dcb 文件管理
//http://blog.csdn.net/louercab/article/details/26556007   coredata mr 的使用
//http://blog.csdn.net/sbvfhp/article/details/47829983      coredata mr 的使用

#import "ZYHellp.h"
#include <ifaddrs.h>
#include <arpa/inet.h>


static NSTimeInterval cacheTime =  (double)604800;

@implementation ZYHellp

+ (instancetype)sharedManager {
    
    static ZYHellp *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[ZYHellp alloc] init];
    });
    return manager;
}

// 删除所有
+ (void) resetCache
{
    [[NSFileManager defaultManager] removeItemAtPath:[ZYHellp cacheDirectory] error:nil];
}
// 根据关键字删除
+ (void)resetCacheForKey:(NSString *)key
{
    [[NSFileManager defaultManager] removeItemAtPath:[[ZYHellp cacheDirectory] stringByAppendingPathComponent:key] error:nil];
}
// 创建文件夹
+ (void)createDirectoryAtDocumentDirectory:(NSString * )directoryName
{
    NSArray *array =  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* path = [[array objectAtIndex:0] stringByAppendingPathComponent:directoryName];
    BOOL bo = [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
    NSAssert(bo,@"创建目录失败");
    //    NSString *result = [path stringByAppendingPathComponent:file];
}

// 获取默认存储路径
+ (NSString*) cacheDirectory
{
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cacheDirectory = [paths objectAtIndex:0];
    cacheDirectory = [cacheDirectory stringByAppendingPathComponent:@"ZYCaches"];
    return cacheDirectory;
}

+ (NSArray *)getAllFloder
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *fileAndFloderArr = [fileManager contentsOfDirectoryAtPath:[self cacheDirectory] error:nil];
    
    NSMutableArray *dirArray = [[NSMutableArray alloc] init];
    for (NSString * file in fileAndFloderArr){
        NSString *paths = [[self cacheDirectory] stringByAppendingPathComponent:file];
        if ( [fileManager fileExistsAtPath:paths]) {
            [dirArray addObject:file];
        }
    }
    return dirArray;
}



+(NSDate *)getWriteDateFor:(NSString *)key
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *filename = [self.cacheDirectory stringByAppendingPathComponent:key];
    NSDate *modificationDate;
     if ([fileManager fileExistsAtPath:filename]){
       modificationDate  = [[fileManager attributesOfItemAtPath:filename error:nil] objectForKey:NSFileModificationDate];
     }
    return modificationDate;
}

+ (NSData *) dataForKey:(NSString*)key
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *filename = [self.cacheDirectory stringByAppendingPathComponent:key];
//  判断是否有文件
    if ([fileManager fileExistsAtPath:filename]){
//      attributesOfItemAtPath   获取文件属性 NSFileModificationDate 获取文件属性的创建时间
        NSDate *modificationDate = [[fileManager attributesOfItemAtPath:filename error:nil] objectForKey:NSFileModificationDate];
//      以当前时间(Now)为基准时间，返回实例保存的时间与当前时间(Now)的时间间隔
        if ([modificationDate timeIntervalSinceNow] > cacheTime) {
            [fileManager removeItemAtPath:filename error:nil];
        } else {
            NSData *data = [NSData dataWithContentsOfFile:filename];
            return data;
        }
    }
    return nil;
}
+ (void) setData:(NSData*)data forKey:(NSString*)key
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *filename = [self.cacheDirectory stringByAppendingPathComponent:key];
    
    BOOL isDir = YES;
    if (![fileManager fileExistsAtPath:self.cacheDirectory isDirectory:&isDir]) {
//        创建一个文件
        [fileManager createDirectoryAtPath:self.cacheDirectory withIntermediateDirectories:NO attributes:nil error:nil];
    }
    NSError *error;
    @try {
        [data writeToFile:filename options:NSDataWritingAtomic error:&error];
    }
    @catch (NSException * e) {
        //TODO: error handling maybe
    }
}

+ (void)setObject:(id)Object forKey:(NSString*)key;
{
    NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:Object];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *filename = [self.cacheDirectory stringByAppendingPathComponent:key];
    BOOL isDir = YES;
    //   判断文件是否存在
    if (![fileManager fileExistsAtPath:self.cacheDirectory isDirectory:&isDir]) {
        [fileManager createDirectoryAtPath:self.cacheDirectory withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSError *error;
    @try {
        [encodedObject writeToFile:filename options:NSDataWritingAtomic error:&error];
    }@catch (NSException * e) {
        //TODO: error handling maybe
    }
}

+ (id) objectForKey:(NSString*)key
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *filename = [self.cacheDirectory stringByAppendingPathComponent:key];
    //  判断是否有文件
    if ([fileManager fileExistsAtPath:filename]){
//       attributesOfItemAtPath   获取文件属性 NSFileModificationDate 获取文件属性的创建时间
        NSDate *modificationDate = [[fileManager attributesOfItemAtPath:filename error:nil] objectForKey:NSFileModificationDate];
        
//      以当前时间(Now)为基准时间，返回实例保存的时间与当前时间(Now)的时间间隔
        if (fabs([modificationDate timeIntervalSinceNow] ) > cacheTime) {
            [fileManager removeItemAtPath:filename error:nil];
        } else {
            NSData *data = [NSData dataWithContentsOfFile:filename];
            id object = [NSKeyedUnarchiver unarchiveObjectWithData:data];
            return object;
        }
    }
    return nil;
}


// 计算某个文件夹下的大小
- (double)jcGetCachesWithPath:(NSString *)directory{
    
    double size = 0;
    NSFileManager *mgr = [NSFileManager defaultManager];
    BOOL isDirectory = NO;
    // 路径是否存在
    BOOL exists = [mgr fileExistsAtPath:directory isDirectory:&isDirectory];
    if (!exists) return size;
    if (isDirectory) { // 文件夹
        // 获得文件夹的大小  == 获得文件夹中所有文件的总大小
        NSDirectoryEnumerator *enumerator = [mgr enumeratorAtPath:directory];
        for (NSString *subpath in enumerator) {
            // 全路径
            NSString *fullSubpath = [directory stringByAppendingPathComponent:subpath];
            // 累加文件大小
            size += [mgr attributesOfItemAtPath:fullSubpath error:nil].fileSize;
        }
    } else { // 文件
        size = [mgr attributesOfItemAtPath:directory error:nil].fileSize;
    }
    return size/1024/1024;
    
}


// 清除所有缓存
- (void)jcClearCache{
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cacheDirectory = [paths objectAtIndex:0];
    NSFileManager *fileManager=[NSFileManager defaultManager];
    
    if ([fileManager fileExistsAtPath:cacheDirectory]) {
        NSArray *childerFiles=[fileManager subpathsAtPath:cacheDirectory];
        for (NSString *fileName in childerFiles) {
            //如有需要，加入条件，过滤掉不想删除的文件
            NSString *absolutePath=[cacheDirectory stringByAppendingPathComponent:fileName];
            [fileManager removeItemAtPath:absolutePath error:nil];
            NSLog(@"---------%@",fileName);
        }
        NSLog(@"完成缓存清除");
    }
    
}




/// id 转data
+ (NSData *) convertByToData:(id)any{
    
    NSMutableData *data = [[NSMutableData alloc] init];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    [archiver encodeObject:any forKey:@"SomeKeyValue"];
    [archiver finishEncoding];
    
    return data;
}
///data类型 转换 id 类型
+ (id) convertByToIdObject:(NSData *)data{
    
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    id myDictionary = [unarchiver decodeObjectForKey:@"SomeKeyValue"] ;
    [unarchiver finishDecoding];
    return myDictionary;
}









- (NSData *)convertByteArrayToData:(NSArray *)byteArray {
    NSInteger c = byteArray.count;
    uint8_t *bytes = malloc(sizeof(*bytes) * c);
    
    unsigned i;
    for (i = 0; i < c; i++) {
        NSString *str = [byteArray objectAtIndex:i];
        int byte = [str intValue];
        bytes[i] = (uint8_t)byte;
    }
    
    return [NSData dataWithBytes:bytes length:c];
}





















- (int)intervalSinceWithOldTime:(NSString *)dateString withNewFormate:(NSString *) formate
{
    int timeDiff  = 0;
    NSDateFormatter *formatters = [[NSDateFormatter alloc]init];
    [formatters setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *dateS = [formatters dateFromString:dateString];
    NSDate *dateE = [formatters dateFromString:formate];
    timeDiff = [dateE timeIntervalSinceDate:dateS ];
    return timeDiff;
}

-(NSString *)getNewData
{
    NSDate *  senddate=[NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *  locationString=[dateformatter stringFromDate:senddate];
    return locationString;
}


+ (NSString *)deviceIPAdress {
    
    NSString *address = @"an error occurred when obtaining ip address";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    
    success = getifaddrs(&interfaces);
    
    if (success == 0) { // 0 表示获取成功
        
        temp_addr = interfaces;
        while (temp_addr != NULL) {
            if( temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if ([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            
            temp_addr = temp_addr->ifa_next;
        }
    }
    
    freeifaddrs(interfaces);
    return address;
}


@end
